package model

import (
	"gin/common/types"
	nlpDict "gin/tai/dict"
	"gorm.io/gorm"
)

type Dict struct {
	Id          uint64           `json:"id" gorm:"column:id;primaryKey;type:int;autoIncrement"`
	DictId      string           `json:"dict_id" gorm:"column:dict_id"`
	Name        string           `json:"name" gorm:"column:name"`
	Description string           `json:"description" gorm:"column:description"`
	Created     types.TstampTime `json:"created" gorm:"column:created;autoCreateTime;type:uint"`
	Updated     types.TstampTime `json:"updated" gorm:"column:updated;autoUpdateTime;type:uint"`
}

// 设置表名
func (Dict) TableName() string {
	return "dict"
}

func (this *Dict) AfterCreate(tx *gorm.DB) (err error) {
	if this.DictId == "" {
		res, err := nlpDict.Create(&this.Name, &this.Description)
		if err != nil {
			return err
		}
		this.DictId = *res.Response.DictId
		tx.Save(&this)
	}

	return err
}

// 在数据被删除后
func (this *Dict) AfterDelete(tx *gorm.DB) (err error) {

	if this.DictId != "" {
		_, err = nlpDict.Delete(this.DictId)
		if err != nil {
			return err
		}
	}
	return err
}

// 在数据更新后
func (this *Dict) AfterUpdate(tx *gorm.DB) (err error) {

	if this.DictId != "" {
		_, err = nlpDict.Update(&this.DictId, &this.Name, &this.Description)
	}

	return err
}
